<template>
  <el-dialog
    v-model="visible"
    title="列配置"
    width="700px"
    :before-close="handleClose"
  >
    <div class="column-config-content">
      <div class="config-section">
        <h4>选择要显示的列</h4>
        <p class="section-desc">拖拽列到右侧来显示，或从右侧拖拽到左侧来隐藏</p>
        
        <div class="columns-container">
          <!-- 可用列 -->
          <div class="available-columns">
            <h5>可用列</h5>
            <div class="column-list">
              <div
                v-for="column in availableColumns"
                :key="column.key"
                class="column-item"
                draggable="true"
                @dragstart="handleDragStart($event, column, 'available')"
                @dragover="handleDragOver($event)"
                @drop="handleDrop($event, column, 'available')"
              >
                <el-icon class="drag-handle"><Rank /></el-icon>
                <span class="column-label">{{ column.label }}</span>
                <span class="column-key">({{ column.key }})</span>
              </div>
            </div>
          </div>
          
          <!-- 已选列 -->
          <div class="selected-columns">
            <h5>已选列</h5>
            <div class="column-list">
              <div
                v-for="(column, index) in selectedColumns"
                :key="column.key"
                class="column-item"
                draggable="true"
                @dragstart="handleDragStart($event, column, 'selected', index)"
                @dragover="handleDragOver($event)"
                @drop="handleDrop($event, column, 'selected', index)"
              >
                <el-icon class="drag-handle"><Rank /></el-icon>
                <span class="column-label">{{ column.label }}</span>
                <span class="column-key">({{ column.key }})</span>
                <el-button
                  type="text"
                  size="small"
                  class="remove-btn"
                  @click="removeColumn(index)"
                >
                  <el-icon><Close /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      

    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Rank, Close } from '@element-plus/icons-vue'

export default {
  name: 'ColumnConfigDialog',
  components: {
    Rank,
    Close
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    columns: {
      type: Array,
      required: true
    },
    allColumns: {
      type: Array,
      required: true
    }
  },
  emits: ['update:modelValue', 'save'],
  setup(props, { emit }) {
    const visible = computed({
      get: () => props.modelValue,
      set: (value) => emit('update:modelValue', value)
    })
    
    // 当前配置的列
    const selectedColumns = ref([])
    
    // 可用列（未选择的列）
    const availableColumns = computed(() => {
      const selectedKeys = selectedColumns.value.map(col => col.key)
      return props.allColumns.filter(col => !selectedKeys.includes(col.key))
    })
    
    // 拖拽状态
    const dragState = ref({
      isDragging: false,
      draggedColumn: null,
      sourceType: null,
      sourceIndex: null
    })
    
    // 初始化配置
    const initConfig = () => {
      console.log('ColumnConfigDialog - 初始化配置')
      console.log('ColumnConfigDialog - props.columns:', props.columns)
      console.log('ColumnConfigDialog - props.allColumns:', props.allColumns)
      
      // 确保从props.columns初始化时包含完整的列定义
      selectedColumns.value = props.columns.map(column => {
        const fullColumn = props.allColumns.find(col => col.key === column.key)
        if (fullColumn) {
          // 从allColumns中获取完整的列定义，包括renderer
          const result = {
            key: column.key,
            label: column.label,
            width: fullColumn.width, // 使用allColumns中的默认宽度
            sortable: fullColumn.sortable, // 使用allColumns中的默认排序设置
            renderer: fullColumn.renderer // 从allColumns中获取renderer
          }
          console.log(`ColumnConfigDialog - 列 ${column.key}:`, result)
          return result
        } else {
          console.log(`ColumnConfigDialog - 列 ${column.key}:`, column)
          return { ...column }
        }
      })
      
      // 确保所有列都有正确的renderer
      selectedColumns.value = ensureRenderers(selectedColumns.value)
      
      console.log('ColumnConfigDialog - 初始化后的selectedColumns:', selectedColumns.value)
    }
    
    // 监听 props 变化，重新初始化
    watch(() => props.columns, initConfig, { immediate: true })
    
    // 拖拽开始
    const handleDragStart = (event, column, type, index) => {
      dragState.value = {
        isDragging: true,
        draggedColumn: column,
        sourceType: type,
        sourceIndex: index
      }
      event.dataTransfer.effectAllowed = 'move'
    }
    
    // 拖拽悬停
    const handleDragOver = (event) => {
      event.preventDefault()
      event.dataTransfer.dropEffect = 'move'
    }
    
    // 拖拽放置
    const handleDrop = (event, targetColumn, targetType, targetIndex) => {
      event.preventDefault()
      
      if (!dragState.value.isDragging) return
      
      const { draggedColumn, sourceType, sourceIndex } = dragState.value
      
      if (sourceType === 'available' && targetType === 'selected') {
        // 从可用列添加到已选列
        addColumn(draggedColumn, targetIndex)
      } else if (sourceType === 'selected' && targetType === 'available') {
        // 从已选列移除
        removeColumn(sourceIndex)
      } else if (sourceType === 'selected' && targetType === 'selected') {
        // 在已选列中重新排序
        reorderColumns(sourceIndex, targetIndex)
      }
      
      dragState.value = {
        isDragging: false,
        draggedColumn: null,
        sourceType: null,
        sourceIndex: null
      }
    }
    
    // 添加列
    const addColumn = (column, index) => {
      // 从allColumns中找到完整的列定义，确保包含所有属性
      const fullColumn = props.allColumns.find(col => col.key === column.key)
      let newColumn
      
      if (fullColumn) {
        // 从allColumns中获取完整的列定义，包括renderer
        newColumn = {
          key: fullColumn.key,
          label: fullColumn.label,
          width: fullColumn.width, // 使用allColumns中的默认宽度
          sortable: fullColumn.sortable, // 使用allColumns中的默认排序设置
          renderer: fullColumn.renderer // 从allColumns中获取renderer
        }
      } else {
        newColumn = { ...column }
      }
      
      if (index !== undefined) {
        selectedColumns.value.splice(index, 0, newColumn)
      } else {
        selectedColumns.value.push(newColumn)
      }
    }
    
    // 移除列
    const removeColumn = (index) => {
      selectedColumns.value.splice(index, 1)
    }
    
    // 重新排序列
    const reorderColumns = (fromIndex, toIndex) => {
      const column = selectedColumns.value.splice(fromIndex, 1)[0]
      selectedColumns.value.splice(toIndex, 0, column)
    }
    
    // 确保列配置包含正确的renderer
    const ensureRenderers = (columns) => {
      return columns.map(column => {
        const fullColumn = props.allColumns.find(col => col.key === column.key)
        if (fullColumn && fullColumn.renderer) {
          return {
            ...column,
            renderer: fullColumn.renderer // 确保renderer来自allColumns
          }
        }
        return column
      })
    }
    
    // 重置为默认配置
    const handleReset = () => {
      selectedColumns.value = props.allColumns.map(col => ({
        key: col.key,
        label: col.label,
        width: col.width, // 使用allColumns中的默认宽度
        sortable: col.sortable, // 使用allColumns中的默认排序设置
        renderer: col.renderer // 确保renderer被正确复制
      }))
      // 确保所有列都有正确的renderer
      selectedColumns.value = ensureRenderers(selectedColumns.value)
      ElMessage.success('已重置为默认配置')
    }
    
    // 保存配置
    const handleSave = () => {
      if (selectedColumns.value.length === 0) {
        ElMessage.warning('请至少选择一列')
        return
      }
      
      // 确保所有列都有正确的renderer
      const finalColumns = ensureRenderers(selectedColumns.value)
      
      console.log('ColumnConfigDialog - 保存配置:', finalColumns)
      // 检查renderer属性
      finalColumns.forEach(col => {
        console.log(`ColumnConfigDialog - 保存时列 ${col.key} 的renderer:`, col.renderer)
      })
      emit('save', finalColumns)
      visible.value = false
    }
    
    // 关闭对话框
    const handleClose = () => {
      visible.value = false
    }
    
    return {
      visible,
      selectedColumns,
      availableColumns,
      handleDragStart,
      handleDragOver,
      handleDrop,
      removeColumn,
      handleSave,
      handleClose
    }
  }
}
</script>

<style scoped>
.column-config-content {
  max-height: 500px;
  overflow-y: auto;
}

.config-section {
  margin-bottom: 24px;
}

.config-section h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
}

.section-desc {
  margin: 0 0 16px 0;
  color: #606266;
  font-size: 14px;
}

.columns-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.available-columns,
.selected-columns {
  flex: 1;
  min-height: 150px;
  min-width: 250px;
}

.available-columns h5,
.selected-columns h5 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
}

.column-list {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 150px;
  padding: 8px;
  background: #fafafa;
}

.column-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 4px;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: move;
  transition: all 0.2s;
}

.column-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.column-item:last-child {
  margin-bottom: 0;
}

.drag-handle {
  margin-right: 8px;
  color: #909399;
  cursor: move;
  flex-shrink: 0;
}

.column-label {
  flex: 1;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 4px;
}

.column-key {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
  white-space: nowrap;
  flex-shrink: 0;
}

.remove-btn {
  margin-left: 8px;
  color: #f56c6c;
  flex-shrink: 0;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 